import { cloneDeep } from "lodash-es"
import ChinaProvinceData from "province-city-china/dist/level.json"

interface addressType {
  value: string
  label: string
  children?: addressType[]
}

export const addressCascaderOpts = transformAddressCascaderOpts()

function transformAddressCascaderOpts(data = ChinaProvinceData) {
  const addressData: addressType[] = []
  data.forEach((item, index) => {
    const { code: value, name: label, children } = item
    addressData[index] = {
      value,
      label,
      children: Array.isArray(children) ? transformAddressCascaderOpts(children as any) : undefined
    }
  })
  return addressData
}

// 根据地址codes数组来获取地址详情
export function getAddressDetails(codes: [number?, number?, number?], data = addressCascaderOpts) {
  let tempObj: addressType[] = cloneDeep(data)
  const copyCodes = codes.slice()
  let address = ""

  do {
    const [code] = copyCodes
    const [dataObj] = tempObj.filter((item: any) => Number(item.value) === code)
    address += dataObj?.label ?? ""
    // @ts-expect-error
    tempObj = dataObj?.children
    copyCodes.shift()
  } while (copyCodes.length !== 0)
  return address
}

// 转换地址为string，以方便提交给服务器
export function transformAddressToString(codes: [(number | string)?, (number | string)?, (number | string)?] | string) {
  const copyCodes = cloneDeep(codes)
  if (typeof copyCodes === "string") return copyCodes
  return JSON.stringify(copyCodes.map((item) => Number(item)))
}

// 获取资源的标签
interface ResourcesItemOptsParams {
  resource: { label: string; value: number }[]
  key?: keyof ResourcesItemOptsParams["resource"][number]
}
export function getResourceData(val: number | string, { resource, key }: ResourcesItemOptsParams) {
  const valNum = Number(val)
  const [tagItem] = resource.filter((item) => item.value === valNum)
  return key ? tagItem[key] : tagItem
}
